<template>
	<view>
		<form id="bhzdForm" @submit="formSubmit">
			<view class="cu-form-group">
				<view class="title">作物类型</view>
				<picker v-model="diagnose.cropType" name="cropType" @change="pickerChange" :value="cropTypeIndex" :range="cropTypeNameArr">
					<view class="picker">
						{{cropTypeIndex>-1?cropTypeNameArr[cropTypeIndex]:'选择作物种类'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">部位</view>
				<picker v-model="diagnose.organName" name="organName" @change="pickerChangeOrgan" :value="organIndex" :range="organNameArr">
					<view class="picker">
						{{organIndex>-1?organNameArr[organIndex]:'选择部位'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">生长期</view>
				<picker v-model="diagnose.periodName" name="periodName" @change="pickerChangePeriod" :value="periodIndex" :range="periodNameArr">
					<view class="picker">
						{{periodIndex>-1?periodNameArr[periodIndex]:'选择生长期'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">发病日期</view>
				<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="DateChange">
					<view class="picker">
						{{date}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<textarea placeholder="症状描述" name="symptom" v-model="diagnose.symptom"></textarea>
			</view>
			<view class="cu-form-group">
				<view class="action">
					图片上传
				</view>
				<view class="action">
					{{imgList.length}}/10
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img margin-top" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
						<image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close' name="photo"></text>
						</view>
					</view>
					<view class="solids margin-top" @tap="ChooseImage" v-if="imgList.length<10">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class="action">
					<text class="cuIcon-list text-blue"></text>诊断结果
				</view>
			</view>
			<view class="" v-if="resultList.length==0">
				<view class="padding text-center">
					<view class="padding-lr bg-white">
						<view class="padding">{{emptyResult}}</view>
					</view>
				</view>
			</view>
			<view v-for="(value, key) in resultList" :key="key" >
				<view class="cu-bar bg-white solid-bottom  solids-bottom">
					<view class="action">
						<text class="cuIcon-titles text-orange"></text> {{value.diagnoses}}
					</view>
				</view>
				<view class="cu-card case no-card">
					<view class="cu-item shadow">
						<view class="solid-bottom text-sm padding">
							<view class="text-grey">
								<rich-text type="text" :nodes="value.solution"></rich-text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="padding">
				<view class="cu-bar btn-group">
					<button form="bhzdForm" form-type="submit" class="cu-btn bg-green shadow-blur round lg block margin-tb-sm" :disabled="btn_disabled" :type="btn_type"
					 :loading="btn_loading">诊断</button>
				</view>
			</view>
		</form>
	</view>
</template>

<script>
	var graceChecker = require("../../plugin/graceUI/jsTools/graceChecker.js");
	var graceRichText = require("../../plugin/graceUI/jsTools/richText.js");
	//获取日期
	function getDate(type) {
		const date = new Date();

		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();

		if (type === 'start') {
			year = year - 5;
		} else if (type === 'end') {
			year = year;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;

		return `${year}-${month}-${day}`;
	}
	export default {
		data() {
			return {
				//当前选择的开始时间
				imgindex: 0,
				date: getDate({
					format: true
				}),
				//时间选择限制条件-start
				startDate: getDate('start'),
				//时间选择限制条件-end
				endDate: getDate('end'),

				cropTypeIndex: 0, //作物种类
				cropTypeNameArr: [],
				cropTypeIdArr: [],
				organIndex: 0, //部位
				organNameArr: [],
				organIdArr: [],
				periodIndex: 0, //生长期
				periodNameArr: [],
				periodIdArr: [],

				btn_disabled: false,
				btn_type: '',
				btn_loading: false,
				diagnose: { //诊断
					id: '',
					userid: '',
					cropType: '',
					cropid: '',
					organName: '',
					organid: '',
					periodid: '',
					periodName: '',
					symptom: '', //症状描述
					diseasepics: '', //上传后的相对路径
					diseasetime: ''
				},
				imgList: [],//转换后的图像地址
				tempImgSrc: '',//当前要操作的图片路径，上传或者删除
				resultList:[],//诊断结果
				emptyResult:'',
			};
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			if (option.id) {
				this.diagnose.id = option.id;
			} else {
				this.diagnose.id = "";
			}
			this.getDiagnose();

		},
		methods: {
			DateChange(e) {
				this.date = e.detail.value;
			},
			pickerChange(e) {
				this.cropTypeIndex = e.detail.value;
				this.diagnose.cropType = this.cropTypeNameArr[this.cropTypeIndex];
				this.diagnose.cropid = this.cropTypeIdArr[this.cropTypeIndex]
				this.organIndex = 0; //重置部位
				this.getOrgan();
				this.getPeriod();
			},
			pickerChangeOrgan(e) {
				this.organIndex = e.detail.value;
				this.diagnose.organName = this.organNameArr[this.organIndex];
				this.diagnose.organid = this.organIdArr[this.organIndex];
			},
			pickerChangePeriod(e) {
				this.periodIndex = e.detail.value;
				this.diagnose.periodName = this.periodNameArr[this.periodIndex];
				this.diagnose.periodid = this.periodIdArr[this.organIndex];
			},

			//根据id获取信息
			getDiagnose() {
				var id = '';
				if (this.diagnose.id == '') {
					id = 'add_flag'; //后台不允许id为空
				} else {
					id = this.diagnose.id
				}
				uni.request({
					url: this.$config.apiUrl + "/diseaseController/" + id,
					success: (res) => {
						// console.log(res);
						if (res.data.data != null) {
							this.diagnose = res.data.data;
							//图片
							let photoUrl = [];
							photoUrl = (this.diagnose.diseasepics == null || this.diagnose.diseasepics == "") ? '' : this.diagnose.diseasepics
								.split(",");
							for (var i = 0; i < photoUrl.length; i++) {
								if (photoUrl[i] != '' && photoUrl[i] != null) {
									var imgURL = this.$config.imgUrl + '/' + photoUrl[i];
									this.imgList.push(imgURL);
									this.tempImgSrc = photoUrl[i];
								}
							}
							this.cropTypeNameArr = this.diagnose.extMap.cropTypeNameArr;
							this.cropTypeIdArr = this.diagnose.extMap.cropTypeIdArr;
							this.cropTypeIdArr.forEach((item, index) => {
								if (item == this.diagnose.cropid) {
									this.cropTypeIndex = index;
								}
							});
							if (this.diagnose.diseasetime) {
								this.date = this.diagnose.diseasetime;
							}

							this.getOrgan();
							this.getPeriod();
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "查询失败",
							icon: "none"
						});
					},
					complete: () => {}
				});
			},
			//根据作物id获取部位
			getOrgan() {
				uni.request({
					url: this.$config.apiUrl + "/diseaseController/getOrgan",
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //这样设置request才能接值
					},
					data: {
						cropid: this.cropTypeIdArr[this.cropTypeIndex]
					},
					success: (res) => {
						// console.log(res);
						if (res.data.data != null) {
							let organList = [];
							this.organNameArr = [];
							this.organIdArr = [];
							organList = res.data.data;
							// console.log(this.orgInfo.orgCode);\\
							organList.forEach((item, index) => {
								this.organNameArr.push(item.name);
								this.organIdArr.push(item.id);
							});
							this.organIdArr.forEach((item, index) => {
								if (item == this.diagnose.organid) {
									this.organIndex = index;
								}
							});
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "查询失败",
							icon: "none"
						});
					},
					complete: () => {}
				});
			},
			//根据作物id获取生长期
			getPeriod() {
				uni.request({
					url: this.$config.apiUrl + "/diseaseController/getPeriod",
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //这样设置request才能接值
					},
					data: {
						cropid: this.cropTypeIdArr[this.cropTypeIndex]
					},
					success: (res) => {
						// console.log(res);
						if (res.data.data != null) {
							let periodList = [];
							this.periodNameArr = [];
							this.periodIdArr = [];
							periodList = res.data.data;
							// console.log(this.orgInfo.orgCode);\\
							periodList.forEach((item, index) => {
								this.periodNameArr.push(item.name);
								this.periodIdArr.push(item.id);
							});
							this.periodIdArr.forEach((item, index) => {
								if (item == this.diagnose.periodid) {
									this.periodIndex = index;
								}
							});
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "查询失败",
							icon: "none"
						});
					},
					complete: () => {}
				});
			},
			//获取诊断结果
			getDiagnoseResult() {
				uni.request({
					url: this.$config.apiUrl + "/diseaseController/getDiagnoseResult",
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //这样设置request才能接值
					},
					data: {
						diagnoseid: this.diagnose.id
					},
					success: (res) => {
						// console.log(res);
						if(res.data.data!=null){
							let d=res.data.data;
							this.resultList=d.result;
							if(this.resultList.length==0){
								this.emptyResult="未能给出自动诊断!";
							}else{
								this.resultList.forEach((item,index)=>{
									// item.diagnoses//诊断结果
									// item.solution//解决方案
									item.solution = graceRichText.format(item.solution);
								});
							}
							uni.showToast({
								title: res.data.message,
								duration: 2000,
								icon: "none"
							});
							this.btn_loading = false;
							this.btn_disabled = false;
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "查询失败",
							icon: "none"
						});
					},
					complete: () => {}
				});
			},
			ChooseImage() {
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						
						 for(let i=this.imgindex;i<this.imgList.length;i++,this.imgindex++){
						 	this.tempImgSrc = this.imgList[i];
						 	this.dealFile(1, 0, '');
						 }
						 // this.tempImgSrc=res.tempFilePaths[0];
						 // this.dealFile(1,0,'');
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '删除照片',
					content: '确定要删除吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							if(this.diagnose.id){
								let lj=this.imgList[e.currentTarget.dataset.index];
								let index=lj.indexOf("server");
								this.tempImgSrc=lj.substring(index+7,lj.length);
								this.dealFile(0,1,this.tempImgSrc);
							}
							// console.log("delPath",this.tempImgSrc);
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			//处理附件
			dealFile(isup, isdel, delPath) {
				uni.uploadFile({
					url: this.$config.apiUrl + "/appUploadController/dealFile",
					filePath: this.tempImgSrc, //当前要操作的图片路径，上传或者删除
					fileType: 'image',
					name: 'file', //后端通过'file'获取上传的文件对象
					formData: {
						isup: isup,
						isdel: isdel,
						bizType: 'photosucai',
						delPath: delPath
					},
					success: (res) => {
						// console.log(res)
						if (res.statusCode === 200) {
							let data = JSON.parse(res.data);
							let msg = data.message;
							if (isup == 1) {
								if (this.diagnose.diseasepics) {
									this.diagnose.diseasepics += ',' + data.data;
								} else {
									this.diagnose.diseasepics = data.data;
								}
							} else {
								//删除照片及逗号，三次匹配
								this.diagnose.diseasepics = this.diagnose.diseasepics.replace(',' + delPath, '');
								this.diagnose.diseasepics = this.diagnose.diseasepics.replace(delPath + ',', '');
								this.diagnose.diseasepics = this.diagnose.diseasepics.replace(delPath, '');
							}
							// console.log(this.diagnose.photo);
							uni.showToast({
								title: msg,
								duration: 2000
							});
							this.tempImgSrc = "";
						}
					},
					fail: (res) => {
						console.log(res)
					}
				});
			},

			// 表单提交及验证
			formSubmit: function(e) {
				//定义表单规则
				var rule = [{
						name: "cropType",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "作物类别不能为空!"
					},
					{
						name: "organName",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "部位不能为空!"
					},
					{
						name: "periodName",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "生长期不能为空!"
					},
					{
						name: "symptom",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "描述不能为空!"
					},
					{
						name: "diseasepics",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "图片不能为空!"
					},
				];
				//进行表单检查 e.detail.value 内存放着表单数据
				let formData = e.detail.value;
				formData.id = this.diagnose.id == null ? '' : this.diagnose.id;
				formData.userId = this.$store.getters.userid;
				formData.cropid = this.cropTypeIdArr[this.cropTypeIndex];
				formData.organid = this.organIdArr[this.organIndex];
				formData.periodid = this.periodIdArr[this.periodIndex];
				formData.diseasepics = this.diagnose.diseasepics;
				formData.symptom = this.diagnose.symptom;
				formData.diseasetime = this.date;

				//校验使用
				formData.cropType = this.cropTypeNameArr[this.cropTypeIndex];
				formData.organName = this.organNameArr[this.organIndex];
				formData.periodName = this.periodNameArr[this.periodIndex];
				var checkRes = graceChecker.check(formData, rule);
				if (checkRes) {
					this.btn_loading = true;
					this.btn_disabled = true;
					uni.request({
						url: this.$config.apiUrl + "/diseaseController/saveDiagnose",
						method: 'POST',
						header: {
							'content-type': 'application/x-www-form-urlencoded' //这样设置request才能接值
						},
						data: formData,
						success: (res) => {
							//console.log(res);
							if (res.data.ok) {
								let d = res.data.data;
								this.diagnose.id = d.id;
								this.getDiagnoseResult();

							} else {
								uni.showToast({
									title: res.data.message,
									duration: 2000,
									icon: "none"
								});
								this.btn_loading = false;
								this.btn_disabled = false;
							}

						},
						fail: (res) => {
							console.log(res);
						},
						complete: () => {}
					});
				} else {
					uni.showToast({
						title: graceChecker.error,
						icon: "none"
					});
				}
			}
		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
</style>
